package com.compty.paint.manager;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.compty.core.framework.util.DateUtil;
import com.compty.core.hibernate.HibernateEntityDao;
import com.compty.core.page.Page;
import com.compty.paint.domain.AuditState;
import com.compty.paint.domain.Painter;
import com.compty.paint.domain.Painting;
import com.compty.paint.domain.UploadState;
import com.compty.paint.util.Constants;
import com.compty.security.domain.User;

public class PainterManager  extends HibernateEntityDao<Painter>{
	
	private PaintingManager paintingManager;
	private UploadStateManager uploadStateManager;
	private AuditStateManager auditStateManager;

	public void setPaintingManager(PaintingManager paintingManager) {
		this.paintingManager = paintingManager;
	}

	public void setUploadStateManager(UploadStateManager uploadStateManager) {
		this.uploadStateManager = uploadStateManager;
	}

	public void setAuditStateManager(AuditStateManager auditStateManager) {
		this.auditStateManager = auditStateManager;
	}
	
	/**
	 * 删除艺术家
	 */
	@SuppressWarnings("unchecked")
	public void removeById(Serializable id) {
		 
		 String hql = "select p.id from Painting p where p.painter.id= ? ";
		 List list = find(hql, id);
		 
		 for (int i = 0; i < list.size(); i++) {
			  Long 	painting_id = (Long) list.get(i);
			  paintingManager.removeById(painting_id);
		 }
		 
	     super.removeById(id);
	 }
	
	/**
	 *@Todo:分页查询名家
	 *@CreateTime:2011-8-18 上午11:31:21
	 * @param curPage 当前页码
	 * @param pageSize  显示条数
	 */
	public Page findPainterStarByPage(int curPage, int pageSize,String decade){
		
		Criteria criteria = createCriteria();
		
        UploadState  uploadState = uploadStateManager.findUniqueBy("english_name", Constants.Upload_State_Init); //上传状态正常
        criteria = criteria.add(Restrictions.eq("uploadState", uploadState)); 
        AuditState auditState = auditStateManager.findUniqueBy("english_name", Constants.Audit_State_Pass);  //审核状态通过
        criteria = criteria.add(Restrictions.eq("auditState", auditState)); 
        
        criteria.add(Restrictions.eq("type", "2"));
        
        if(decade != null){
        	  criteria.add(Restrictions.eq("decade", decade));
        }
      
		return super.pagedQuery(criteria, curPage,pageSize);
	}


	/**
	 *@Todo:根据年代查找艺术家(名家)
	 *@CreateTime:2011-8-25 上午10:56:13
	 * @param decade
	 */
	@SuppressWarnings("unchecked")
	public List<Painter> findPaintersByDecade(String decade) {
		if(decade != null && !"".equals( decade) ){
			String hql = " from Painter where decade = ? and type=2 ";
			return  super.find(hql, decade);
		}else{
			String hql  = " from Painter where  type = 2 ";
			return  super.find(hql);
		}
	}

	/**
	 *@Todo:通过艺术家名字及录入人查找艺术家
	 * @param name  艺术家名字
	 * @param user 录入人
	 */
	@SuppressWarnings("unchecked")
	public List<Painter> findByPainterNameAndEntryPerson(String name,User user) {
		String hql = " from Painter where name = ? and entryPerson = ? ";
		return paintingManager.find(hql,name,user);
	}
	
	/**
	 *@Todo:通过艺术家名字查找艺术家
	 * @param name  艺术家名字
	 */
	@SuppressWarnings("unchecked")
	public List<Painter> findByPainterName(String name) {
		String hql = " from Painter where name = ? ";
		return paintingManager.find(hql,name);
	}
	
	/**
	 *@Todo:已有艺术家(客座画家(非名家))列表，根据录入者查询画家列表
	 *@CreateTime:2011-8-30 上午10:22:43
	 * @param user 录入者
	 * @return List<Painter> 艺术家列表
	 */
	@SuppressWarnings("unchecked")
	public List<Painter> findByEntryPerson(Long userId,String administratorFlag){
		
		if("1".equals(administratorFlag)){ //如果是管理员用户
			
			String hql = " from Painter where  type = 1";
			
			return find(hql);
			
		}else{
			
			String hql = " from Painter where entryPerson.id = ? and type = 1";
			
			return find(hql, userId);
		}
	}

	/**
	 *@Todo:查找国画名家
	 *@author:朱庆辉
	 *@CreateTime:2012-4-12 上午10:57:34
	 */
	@SuppressWarnings("unchecked")
	public List<Painter> findGuohuaPainerStar() {
		String hql  = " from Painter where  type = 2 and (decade = 1  or decade = 3 or decade = 5 )";
		List<Painter> list =  super.find(hql);
		return list;
	}

	/**
	 *@Todo:查找油画名家
	 *@author:朱庆辉
	 *@CreateTime:2012-4-12 上午10:58:03
	 */
	@SuppressWarnings("unchecked")
	public List<Painter> findyouhuaPainerStar() {
		String hql  = " from Painter where  type = 2 and (decade = 2  or decade = 4)";
		
		return  super.find(hql);
	}
	
	/**
	 *@Todo:查找全部名家
	 *@author:朱庆辉
	 *@CreateTime:2012-4-12 上午10:58:26
	 */
	@SuppressWarnings("unchecked")
	public List<Painter> findAllPainerStar() {
		String hql  = " from Painter where  type = 2 ";
		
		return  super.find(hql);
	}

	/**
	 * 根据时期查询名家
	 * @param type 1:当代 2近代 3古代
	 */
	@SuppressWarnings("unchecked")
	public List<Painter> findPaintersByPeriod(String type) {
		if( "1".equals( type) ){
			String hql = " from Painter where (decade = '3' or decade = '4')  and type= '2' ";
			return  super.find(hql);
		}
		else if("2".equals( type) ){
			String hql = " from Painter where (decade = '1' or decade = '2')   and type= '2' ";
			return  super.find(hql);
		}
		else if("3".equals( type) ){
			String hql = " from Painter where decade = '5' and type= '2' ";
			return  super.find(hql);
		}
		else{
			String hql  = " from Painter where  type = '2' ";
			return  super.find(hql);
		}
	}

	/**
	 * 根据画家类型查找客座画家
	 * @param painterName 画家名家
	 * @param catalogType 画种类别
	 */
	public Page queryPaintersByNameAndCatalogtype(Integer curPage, Integer pageSize,String painterName, String catalogType) {
		String hql = " from Painter where  type = 1 ";
		Object[] values = new Object[0];
		if( painterName != null && !"".equals(painterName)){
			hql += " and name = ? ";
			values = org.apache.commons.lang.ArrayUtils.add(values, painterName);
		}
		if(catalogType != null && !"".equals(catalogType)){
			hql += " and catalogType.id = ? ";
			values = org.apache.commons.lang.ArrayUtils.add(values, Long.valueOf(catalogType));
		}
		
		return super.pagedQuery(hql, curPage, pageSize, values);
	}

	/**
	 * 由画家汉语拼音名字查找画家
	 * @param englishName 汉语拼音
	 */
	public List<Painter> findbyEnglishName(String englishName) {
		if(englishName == null || "".equals(englishName))
			return null;
		englishName = englishName.trim();
		return super.findBy("englishName", englishName);
	}
	
	/**
	* @Description: 隐藏画家及画家作品
	* @param @param painterId
	 */
	public void hiddenPainter(Long painterId){
		Painter painter = get(painterId);
		UploadState  uploadState = uploadStateManager.findUniqueBy("english_name",Constants.Upload_State_Hidden);
		painter.setUploadState(uploadState);
		painter.setModifyTime(Calendar.getInstance().getTime());
		
		List<Painting> paintings = paintingManager.findPaintingsByPainter(painterId);
		for (Painting painting : paintings) {
			painting.setUploadState(uploadState);
			painting.setModifyTime(Calendar.getInstance().getTime());
			paintingManager.save(painting);
		}
		save(painter);
	}
	
	/**
	* @Description: 分页查找画家(排序)
	* @param @param type 画家类型 1:客座画家 2:名家
	* @param @param startDate 录入时间起始
	* @param @param endDate 录入时间结尾
	* @param @param userInfo 当前登录用户
	* @param @param auditStateType 审核级别ID
	* @param @param filterTxt 查询条件字段名
	* @param @param filterValue 查询条件值
	* @return Page
	 */
	public Page findPainterByPage(final String type,final Date startDate, final Date endDate,final User userInfo,final String auditStateType,
			final String filterTxt,final String filterValue,final Integer catalogtype_id,final Integer curPage, final Integer pageSize){
		
		List list  =  (List)this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				String sql = "select a.* from t_painter a where ";
				
				if( type != null && "1".equals(type)){
					sql += " a.type = '1' ";
				}else{
					sql += " a.type = '2' ";
				}
				
				if(auditStateType != null && !"all".equals(auditStateType)){
					String auditStateTypeId = StringEscapeUtils.escapeSql(auditStateType);
					sql += " a.auditstate_id = " + auditStateTypeId;
				}
				
				if(startDate != null){
					sql += " and  a.uploadtime >=  '"+ DateUtil.toString(startDate, null)+"'";
				}
				
				if(endDate != null){
					sql += " and  a.uploadtime < '"+ DateUtil.toString(endDate, null)+"'";
				}
				
				if(userInfo != null && "0".equals(userInfo.getAdministratorFlag())){
					sql += " and a.userinfo_id = "+userInfo.getId();
				}
				
				if ((filterTxt != null) && (filterValue != null)&& (!filterTxt.equals("")) && (!filterValue.equals(""))) {
					String paramValue = StringEscapeUtils.escapeSql(filterValue);
					sql += " and a."+filterTxt+" like '%"+paramValue+"%'";
				}
				
				if( catalogtype_id != null){
					if(catalogtype_id == 0){
						sql += " and ( a.catalogtype_id = 1 or a.catalogtype_id = 2) ";
					}else{
						sql += " and a.catalogtype_id = "+catalogtype_id;	
					}
				}
				
				sql += " order by case when a.order_no IS NULL THEN 1 ELSE 0 END,a.order_no,a.sortflag desc,a.id desc ";
				
				SQLQuery query = session.createSQLQuery(sql);
				query.setFirstResult((curPage-1)*pageSize);
				query.setMaxResults(pageSize);
				
				List list = query.addEntity(Painter.class).list();
				
				return list;
			}
		});
		
		Integer totalCount  =  (Integer)this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				String sql = "select count(*) as totalCount from t_painter a where ";
				
				if( type != null && "1".equals(type)){
					sql += " a.type = '1' ";
				}else{
					sql += " a.type = '2' ";
				}
				
				if(auditStateType != null && !"all".equals(auditStateType)){
					String auditStateTypeId = StringEscapeUtils.escapeSql(auditStateType);
					sql += " a.auditstate_id = " + auditStateTypeId;
				}
				
				if(startDate != null){
					sql += " and  a.uploadtime >=  '"+ DateUtil.toString(startDate, null)+"'";
				}
				
				if(endDate != null){
					sql += " and  a.uploadtime < '"+ DateUtil.toString(endDate, null)+"'";
				}
				
				if(userInfo != null && "0".equals(userInfo.getAdministratorFlag())){
					sql += " and a.userinfo_id = "+userInfo.getId();
				}
				
				if ((filterTxt != null) && (filterValue != null)&& (!filterTxt.equals("")) && (!filterValue.equals(""))) {
					String paramValue = StringEscapeUtils.escapeSql(filterValue);
					sql += " and a."+filterTxt+" like '%"+paramValue+"%'";
				}
				
				if( catalogtype_id != null){
					if(catalogtype_id == 0){
						sql += " and ( a.catalogtype_id = 1 or a.catalogtype_id = 2) ";
					}else{
						sql += " and a.catalogtype_id = "+catalogtype_id;	
					}
				}
				
				SQLQuery query = session.createSQLQuery(sql);
				return query.addScalar("totalCount", Hibernate.INTEGER).uniqueResult();
			}
		});
		
		Page page = new Page();
		page.setTotalCount(totalCount);
		page.setPageNo(curPage);
		page.setPageSize(pageSize);
		page.setResult(list);
		
		return page;
	}

}
